package com.cater.sys.controller;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.cater.sys.entity.Filestorage;
import com.cater.sys.service.FilestorageService;
import com.cater.utils.RandomUtil;


/**
 * 公用File Controller
 * @author sd
 *
 */
@Controller
@RequestMapping("/filestorage")
public class FilestorageController{
	
	@Autowired
	 FilestorageService service; 
	
	/**
	 * 删除文件
	 * @param id
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deletefile")
	public List<Filestorage> deletefile(String id,String ids,String attributetype,HttpServletRequest request){
		String realPath=request.getSession().getServletContext().getRealPath("/")+"static/upload/";
		Filestorage filestorage = service.getById(id);
	    File file = new File(realPath+filestorage.getFlieName());
	    if(file.exists()){
	    	file.delete();
	    }
	    service.delete(id);
		return service.getAllByattributeId(ids,attributetype);
	}
	
	/**
	 * 查询图片
	 * @param id
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getimglist")
	public List<Filestorage> getimglist(String id,String attributetype,HttpServletRequest request){
		return service.getAllByattributeId(id,attributetype);
	}
	
	@ResponseBody
	@RequestMapping("/uploadimg")
	public JSONObject uploadimg(@RequestParam("fileimg") MultipartFile[] files, HttpServletRequest request) {
		JSONObject json = new JSONObject();
		String realPath = request.getSession().getServletContext().getRealPath("/") + "/static/upload/editor/";
		File filereal = new File(realPath);
		if (!filereal.exists()) {
			filereal.mkdirs();
		}
		String fileName = null;
		List<String> list = new ArrayList<String>();
		try {
			for (MultipartFile file : files) {
				fileName = file.getOriginalFilename();
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				fileName = RandomUtil.generateUpperString(11) + "." + suffix;
				File saveDir = new File(realPath + fileName);
				if (!saveDir.getParentFile().exists())
					saveDir.getParentFile().mkdirs();
				// 转存文件
				file.transferTo(saveDir);
				list.add(request.getContextPath()+"/static/upload/editor/" + fileName);
			}
			json.put("errno", 0);
			json.put("data", list);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;// 跳转的页面
	}
}
